//
//  FieldObservationComm.m
//  Tazama NGO
//
//  Created by jsheriff on 8/11/11.
//  Copyright 2011 The MITRE Corporation. All rights reserved.
//

#import "FieldObservationComm.h"
#import "Notifications.h"
#import "Settings.h"
#import "NSData+Base64.h"
#import "MTEDXLBuilder.h"
#import "MTWebServiceClientManager.h"

@implementation FieldObservationComm

static FieldObservationComm *sharedInstance = nil;

+ (FieldObservationComm *)sharedInstance
{
    if (sharedInstance == nil) {
        sharedInstance = [[super allocWithZone:NULL] init];
    }
    return sharedInstance;
}

+ (id)allocWithZone:(NSZone *)zone
{
    return [[self sharedInstance] retain];
}

- (id)init
{
    if ((self = [super init]))
	{
    }
    return self;
}

- (id)copyWithZone:(NSZone *)zone
{
    return self;
}

- (id)retain
{
    return self;
}

- (NSUInteger)retainCount
{
    return NSUIntegerMax;  //denotes an object that cannot be released
}

- (oneway void)release
{
    //do nothing
}

- (id)autorelease
{
    return self;
}

-(void) postFieldObservationToServer:(FieldObservation *)fieldObservation {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *hostName = [defaults objectForKey:kHostName];
    NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/PostDE", hostName]];
    //	NSURL *url = [NSURL URLWithString:@"http://ec2-50-17-89-240.compute-1.amazonaws.com/PostDE"];
	NSString *requestBody = [self createXMLRequestVersion0:fieldObservation];
	NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
	[request setHTTPMethod:@"POST"];
	[request setValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];
	[request setHTTPBody:[requestBody dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
	[request setValue:[NSString stringWithFormat:@"%d", [requestBody length]] forHTTPHeaderField:@"Content-Length"];
    request.timeoutInterval = 120.0;
    
    //	NSURLResponse *response;
    //	NSError *error;
    //	[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
	receivedData = [[NSMutableData alloc] initWithCapacity:100];
    lastStatusCode = 0;
    theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
	
    /*
     if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
     NSLog(@"Status = %d", httpResponse.statusCode);
     
     if (httpResponse.statusCode == 200) {
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send FO to server" message:@"Succeeded" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
     [alert show];
     [alert release];
     }
     else {
     UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send FO to server" message:@"Failed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
     [alert show];
     [alert release];
     }
     }
     */
}

-(void) postFieldObservationToServer2:(FieldObservation *)fieldObservation {
    // Get the uuid
    NSString *uuidString = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, fieldObservation.uuid));
    
    // Get the user name
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *userId = [defaults objectForKey:kUserId];
    
    if (userId == nil || userId.length == 0) {
        NSLog(@"User ID not found");
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"E-mail Not Found" message:@"Please enter your e-mail in the settings" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    
    // Object Data
    NSMutableDictionary *objectData = [[NSMutableDictionary alloc] init];
    [objectData setValue:fieldObservation.confidence forKey:@"certainty"];
    [objectData setValue:fieldObservation.immediateNeeds forKey:@"immediateNeeds"];
    [objectData setValue:fieldObservation.observationText forKey:@"observationText"];
    [objectData setValue:[NSDate date] forKey:@"reportDateTime"];
    [objectData setValue:fieldObservation.severity forKey:@"urgency"];
    
    // Georef
    CLLocation *georef = [[CLLocation alloc] initWithLatitude:fieldObservation.location.latitude longitude:fieldObservation.location.longitude];
    [objectData setValue:georef forKey:@"georef"];
    [georef release];
    
    NSString *srpKeywordStr = [defaults objectForKey:sitrepKeyword];
    if (srpKeywordStr == nil || srpKeywordStr.length == 0) {
        srpKeywordStr = @"MobileReport";
    }
    
    // Build the Content Object XML
    NSString *fieldObservationContentObject = [MTEDXLBuilder createFieldObservationContentObjectWithId:uuidString srpKeyword:srpKeywordStr observationId:uuidString preparedBy:userId objectData:objectData];
    
    [objectData release];
    
    // Content Objects
    NSMutableArray *contentObjectArray = [[NSMutableArray alloc] init];
    [contentObjectArray addObject:fieldObservationContentObject];
    
    // Add an image if there is one
    if (fieldObservation.image != nil) {
        
        NSData *imageData = UIImageJPEGRepresentation(fieldObservation.image, 1.0);
        NSString *encodedImageData = [imageData base64EncodedString];
        NSString *imageContentObject = [MTEDXLBuilder createNonXmlContentObjectWithContentDescription:@"SitRep Image 1" srpKeyword:srpKeywordStr mimeType:@"image/jpeg" observationId:uuidString 
                                                                                           preparedBy:userId messageId:uuidString contentData:encodedImageData];
        [contentObjectArray addObject:imageContentObject];
    }    
    
    // Build the EDXL
    NSString *edxl = [MTEDXLBuilder createDistributionElementWithId:uuidString senderId:userId dateTimeSent:[NSDate date] distributionStatus:@"Test" location:fieldObservation.location distributionType:@"Report" combinedConfidentiality:@"Unclass" language:@"en-US" contentObjects:contentObjectArray];
    
    [contentObjectArray release];
    
    NSString *hostName = [defaults objectForKey:kHostName];
    
    if (hostName == nil || hostName.length == 0)
    {
        NSLog(@"Host Name not found");
            
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Host Name Not Found" message:@"Host name for posting not found. Please enter a valid post URL in settings" delegate:self cancelButtonTitle:nil otherButtonTitles:@"OK", nil];
        [alert show];
        [alert release];
        return;
    }
    
    NSLog(@"Create New Field Observation, sending web service request to host: %@", hostName);

    NSString *url;
    if ([defaults objectForKey:kPort]) {
        if ([hostName rangeOfString:@"http://"].location == NSNotFound) {
            url = [NSString stringWithFormat:@"http://%@:%@/PostDE", hostName, [defaults objectForKey:kPort]];
        }
        else {
            url = [NSString stringWithFormat:@"%@:%@/PostDE", hostName, [defaults objectForKey:kPort]];
        }
    }
    else {
        if ([hostName rangeOfString:@"http://"].location == NSNotFound) {
            url = [NSString stringWithFormat:@"http://%@/PostDE", hostName];
        }
        else {
            url = [NSString stringWithFormat:@"%@/PostDE", hostName];
        }
    }
    [[MTWebServiceClientManager sharedManager] postRequestWithId:fieldObservation.uuid toUrl:url message:edxl retry:YES];
}

#pragma mark -
#pragma mark Server Connection Stuff

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    // This method is called when the server has determined that it
    // has enough information to create the NSURLResponse.
	
    // It can be called multiple times, for example in the case of a
    // redirect, so each time we reset the data.
	
    // receivedData is an instance variable declared elsewhere.
    [receivedData setLength:0];
    
    if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
        NSLog(@"Status = %d", httpResponse.statusCode);
        lastStatusCode = httpResponse.statusCode;
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    // Append the new data to receivedData.
    // receivedData is an instance variable declared elsewhere.
    [receivedData appendData:data];
    NSLog(@"didReceiveData length = %d", [data length]);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    // inform the user
    NSLog(@"Connection failed! Error - %@ %@", [error localizedDescription], [[error userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
    
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send FO to server" message:@"Failed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
    [alert show];
    [alert release];

    // release the connection, and the data object
    [theConnection release];
    [receivedData release];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    // do something with the data
    // receivedData is declared as a method instance elsewhere
    NSLog(@"connectionDidFinishLoading: Received %d bytes of data", [receivedData length]);
    
    if (lastStatusCode == 200) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send FO to server" message:@"Succeeded" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
        [alert show];
        [alert release];
    }
    else {
        NSString *serverResponse = [[NSString alloc] initWithData:receivedData encoding:NSASCIIStringEncoding];
        NSLog(@"Server Response: %@", serverResponse);
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Send FO to server" message:@"Failed" delegate:nil cancelButtonTitle:@"Ok" otherButtonTitles:nil];        
        [alert show];
        [alert release];
    }
	
    // release the connection, and the data object
    [theConnection release];
    [receivedData release];
}


-(NSString *)createXMLRequestVersion1:(FieldObservation *)fieldObservation {
    NSString *edxlClause = @"<EDXLDistribution xmlns=\"urn:oasis:names:tc:emergency:EDXL:DE:1.0\">";
    NSString *edxlEndClause = @"</EDXLDistribution>";
    
    NSString *uuidString = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, fieldObservation.uuid));
    NSString *distributionIdClause = [NSString stringWithFormat:@"<distributionID>%@</distributionID>", uuidString];
    
    NSString *userId = @"COIN1@ngo.org";
    NSString *senderClause = [NSString stringWithFormat:@"<senderID>%@</senderID>", userId];
    
    NSDate *today = [NSDate date];
    NSLocale *enUSPOSIXLocale;
    NSDateFormatter *sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
    [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    
    NSString *currentDateTime = [sRFC3339DateFormatter stringFromDate:today];
    [sRFC3339DateFormatter release];
    NSString *dateTimeSentClause = [NSString stringWithFormat:@"<dateTimeSent>%@</dateTimeSent>", currentDateTime];
    NSString *distributionClauses = @"<distributionStatus>Test</distributionStatus> <distributionType>Report</distributionType> <combinedConfidentiality>Unclass</combinedConfidentiality> <language>en-US</language>";
    
    NSString *targetAreaClause = [NSString stringWithFormat:@"<targetArea> <circle>%2.4f,%3.4f 0</circle> </targetArea>", fieldObservation.location.latitude, fieldObservation.location.longitude];
    
    NSString *contentClause = @"<contentObject> <contentDescription>SitRep Field Observation</contentDescription> <contentKeyword> <valueListUrn>http://icnet.mitre.org/ValueLists/ContentKeywords</valueListUrn> <value>MEXL-SitRep</value> </contentKeyword> <xmlContent> <embeddedXMLContent>";
    NSString *contentEndClause = @"</embeddedXMLContent> </xmlContent> </contentObject>";
    
    NSString *sitRepClause = @"<SitRep xmlns=\"urn:oasis:names:tc:emergency:EDXL:SitRep:1.0\" xmlns:gml=\"http://www.opengis.net/gml\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xnl=\"urn:oasis:names:tc:ciq:xnl:3\" xmlns:ct=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\" xsi:schemaLocation=\"urn:oasis:names:tc:emergency:EDXL:SitRep:1.0 ../../../../Projects/IC.NET-Doc/SitRep/Schema/SitRep_Schema_DRAFT_v5.xsd\">";
    NSString *sitRepEndClause = @"</SitRep>";
    
    NSString *messageIdClause = [NSString stringWithFormat:@"<MessageID>%@</MessageID>", uuidString];
    
    NSString *userName = @"NGO Test User";
    NSString *preparedByClause = [NSString stringWithFormat:@"<PreparedBy> <PersonDetails xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\"> <PersonName xmlns=\"urn:oasis:names:tc:ciq:xnl:3\"> <NameElement>%@</NameElement> </PersonName> </PersonDetails> <TimeValue xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">%@</TimeValue> </PreparedBy>", userName, currentDateTime];
    
    NSString *authorizedByClause = [NSString stringWithFormat:@"<AuthorizedBy> <PersonDetails xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\"> <PersonName xmlns=\"urn:oasis:names:tc:ciq:xnl:3\"> <NameElement>NGO Test User</NameElement> </PersonName> </PersonDetails> <TimeValue xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">2011-02-03T10:16:41-07:00</TimeValue> </AuthorizedBy>", userName, currentDateTime];
    
    NSString *reportClauses = @"<ReportPurpose>Test Field Observation</ReportPurpose> <ReportNumber>1</ReportNumber> <ReportVersion><ValueListURI xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">http://versionuri</ValueListURI> <Value xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">0.5</Value> </ReportVersion>";
    
    NSString *timeClauses = [NSString stringWithFormat:@"  <ForTimePeriod> <ToDateTime xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">%@</ToDateTime> <FromDateTime xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">%@</FromDateTime> </ForTimePeriod>", currentDateTime, currentDateTime];
    
    NSString *reportTitleClause = @"<ReportTitle>Test Field Observation</ReportTitle>";
    
    NSString *incidentIdClause = [NSString stringWithFormat:@"<IncidentID>%@</IncidentID>", uuidString];
    
    NSString *confidenceClause = [NSString stringWithFormat:@"<ReportConfidence> <ValueListURI xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">http://confidenceuri</ValueListURI> <Value xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">confidence:%@</Value> </ReportConfidence>", fieldObservation.confidence];
    
    NSString *severityClause = [NSString stringWithFormat:@"<Severity> <ValueListURI xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">http://serverityuri</ValueListURI> <Value xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">severity:%@</Value> </Severity>", fieldObservation.severity];
    
    NSString *actionPlanClause = @"<ActionPlan>TestPlan</ActionPlan>";
    
    NSString *fieldObservationReportClause = @"<Report xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:type=\"FieldObservation\">";
    NSString *fieldObservationReportEndClause = @"</Report>";
    
    NSString *observationLocationClause = [NSString stringWithFormat:@"<ObservationLocation><Point xmlns=\"http://www.opengis.net/gml\"><pos>%2.4f,%3.4f</pos> </Point></ObservationLocation>", fieldObservation.location.latitude, fieldObservation.location.longitude];
    
    NSString *immediateNeedsClause = [NSString stringWithFormat:@"<ImmediateNeeds>%@</ImmediateNeeds>", fieldObservation.immediateNeeds];
    
    NSString *observationTextClause = [NSString stringWithFormat:@"<ObservationText>%@</ObservationText>", fieldObservation.observationText];
    
    NSString *requestBody = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@", edxlClause, distributionIdClause, senderClause, dateTimeSentClause, distributionClauses, targetAreaClause, contentClause, sitRepClause, messageIdClause, preparedByClause, authorizedByClause, reportClauses, timeClauses, reportTitleClause, incidentIdClause, confidenceClause, severityClause, actionPlanClause, fieldObservationReportClause, observationLocationClause, immediateNeedsClause, observationTextClause, fieldObservationReportEndClause, sitRepEndClause, contentEndClause,  edxlEndClause];
    
    return requestBody;
}

-(NSString *)createXMLRequestVersion0:(FieldObservation *)fieldObservation {
    NSString *edxlClause = @"<EDXLDistribution xmlns=\"urn:oasis:names:tc:emergency:EDXL:DE:1.0\">";
    NSString *edxlEndClause = @"</EDXLDistribution>";
    
    NSString *uuidString = NSMakeCollectable(CFUUIDCreateString(kCFAllocatorDefault, fieldObservation.uuid));
    NSString *distributionIdClause = [NSString stringWithFormat:@"<distributionID>%@</distributionID>", uuidString];
    
    NSString *userId = @"COIN1@ngo.org";
    NSString *senderClause = [NSString stringWithFormat:@"<senderID>%@</senderID>", userId];
    
    NSDate *today = [NSDate date];
    NSLocale *enUSPOSIXLocale;
    NSDateFormatter *sRFC3339DateFormatter = [[NSDateFormatter alloc] init];
    enUSPOSIXLocale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];
    [sRFC3339DateFormatter setLocale:enUSPOSIXLocale];
    [sRFC3339DateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss'Z'"];
    [sRFC3339DateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];    
    NSString *currentDateTime = [sRFC3339DateFormatter stringFromDate:today];
    [sRFC3339DateFormatter release];
    NSString *dateTimeSentClause = [NSString stringWithFormat:@"<dateTimeSent>%@</dateTimeSent>", currentDateTime];
    NSString *distributionClauses = @"<distributionStatus>Test</distributionStatus> <distributionType>Report</distributionType> <combinedConfidentiality>Unclass</combinedConfidentiality> <language>en-US</language>";
    
    NSString *targetAreaClause = [NSString stringWithFormat:@"<targetArea> <circle>%2.4f,%3.4f 0</circle> </targetArea>", fieldObservation.location.latitude, fieldObservation.location.longitude];
    
    NSString *contentClause = @"<contentObject> <contentDescription>SitRep Field Observation</contentDescription> <contentKeyword> <valueListUrn>http://icnet.mitre.org/ValueLists/ContentKeywords</valueListUrn> <value>MEXL-SitRep</value> <value>MEXL-SitRep FieldObservation</value> </contentKeyword> <xmlContent> <embeddedXMLContent>";
    NSString *contentEndClause = @"</embeddedXMLContent> </xmlContent> </contentObject>";
    
    NSString *sitRepClause = @"<mEXLSR:SitRep xmlns:mEXLSR=\"http://icnet.mitre.org/mEXL/SitRep/\">";
    NSString *sitRepEndClause = @"</mEXLSR:SitRep>";
    
    NSString *observationLocationClause = [NSString stringWithFormat:@"<ObservationLocation xmlns=\"\"><gml:Point xmlns:gml=\"http://www.opengis.net/gml\"><gml:pos>%2.4f %3.4f</gml:pos> </gml:Point></ObservationLocation>", fieldObservation.location.latitude, fieldObservation.location.longitude];
    
    NSString *messageIdClause = [NSString stringWithFormat:@"<MessageID xmlns=\"\">%@</MessageID>", uuidString];
    
    NSString *userName = @"NGO Test User";
    NSString *preparedByClause = [NSString stringWithFormat:@"<PreparedBy xmlns=\"\"><xnl:PersonName xmlns:xnl=\"urn:oasis:names:tc:ciq:xnl:3\"><xnl:NameElement xnl:ElementType=\"Full Name\">%@</xnl:NameElement></xnl:PersonName></PreparedBy>", userName];
    
    //    NSString *authorizedByClause = [NSString stringWithFormat:@"<AuthorizedBy> <PersonDetails xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\"> <PersonName xmlns=\"urn:oasis:names:tc:ciq:xnl:3\"> <NameElement>NGO Test User</NameElement> </PersonName> </PersonDetails> <TimeValue xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">2011-02-03T10:16:41-07:00</TimeValue> </AuthorizedBy>", userName, currentDateTime];
    
    NSString *reportClauses = @"<ReportPurpose>Test Field Observation</ReportPurpose> <ReportNumber>1</ReportNumber> <ReportVersion><ValueListURI xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">http://versionuri</ValueListURI> <Value xmlns=\"urn:oasis:names:tc:emergency:EDXL:CT:1.0\">0.5</Value> </ReportVersion>";
    
    NSString *timeClauses = [NSString stringWithFormat:@"<FromDateTime xmlns=\"\">%@</FromDateTime> <ToDateTime xmlns=\"\">%@</ToDateTime> <PreparedDateTime xmlns=\"\">%@</PreparedDateTime>", currentDateTime, currentDateTime, currentDateTime];
    
    NSString *reportTitleClause = @"<MessageReportType xmlns=\"\">FieldObservation</MessageReportType>";
    
    NSString *incidentIdClause = [NSString stringWithFormat:@"<IncidentID xmlns=\"\">%@</IncidentID>", uuidString];
    
    NSString *confidenceClause = [NSString stringWithFormat:@"<Certainty xmlns=\"\">%@</Certainty>", fieldObservation.confidence];
    
    NSString *severityClause = [NSString stringWithFormat:@"<Urgency xmlns=\"\">%@</Urgency>", fieldObservation.severity];
    
    //    NSString *actionPlanClause = @"<ActionPlan>TestPlan</ActionPlan>";
    
    NSString *fieldObservationReportClause = @"<SituationObservation xmlns=\"\">";
    NSString *fieldObservationReportEndClause = @"</SituationObservation>";
    
    NSString *observationIdClause = [NSString stringWithFormat:@"<ObservationID>%@</ObservationID>", uuidString];
    
    NSString *observationTypeClause = @"<ObservationType>MedicalandPublicHealth</ObservationType>";
    
    NSString *immediateNeedsClause = [NSString stringWithFormat:@"<ImmediateNeeds>%@</ImmediateNeeds>", fieldObservation.immediateNeeds];
    
    NSString *observationTextClause = [NSString stringWithFormat:@"<ObservationText>%@</ObservationText>", fieldObservation.observationText];
    
    NSString *requestBody = nil;
    if (fieldObservation.image == nil) {
        requestBody = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@", edxlClause, distributionIdClause, senderClause, dateTimeSentClause, distributionClauses, targetAreaClause, contentClause, sitRepClause, observationLocationClause, messageIdClause, incidentIdClause, reportClauses, timeClauses, confidenceClause, preparedByClause, reportTitleClause, severityClause, fieldObservationReportClause, observationIdClause, observationTypeClause, observationTextClause, immediateNeedsClause, fieldObservationReportEndClause, sitRepEndClause, contentEndClause, edxlEndClause];    
    }
    else {
        NSData *imageData = UIImageJPEGRepresentation(fieldObservation.image, 1.0);
        NSString *encodedImageData = [imageData base64EncodedString];
        
        NSString *imageContentClause = @"<contentObject> <contentDescription>SitRep Image</contentDescription> <nonXMLContent><mimeType>image/jpeg</mimeType>";
        NSString *imageContentDataClause = [NSString stringWithFormat:@"<contentData>%@</contentData>", encodedImageData];
        NSString *imageContentEndClause = @"</nonXMLContent></contentObject>";
        
        requestBody = [NSString stringWithFormat:@"%@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@ %@", edxlClause, distributionIdClause, senderClause, dateTimeSentClause, distributionClauses, targetAreaClause, contentClause, sitRepClause, observationLocationClause, messageIdClause, incidentIdClause, reportClauses, timeClauses, confidenceClause, preparedByClause, reportTitleClause, severityClause, fieldObservationReportClause, observationIdClause, observationTypeClause, observationTextClause, immediateNeedsClause, fieldObservationReportEndClause, sitRepEndClause, contentEndClause,  imageContentClause, imageContentDataClause, imageContentEndClause, edxlEndClause];
        
    }
        
    NSLog(@"%@", requestBody);
    return requestBody;
}

@end
